package com.asset.dispoal.commom.version;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;


/**
 * @author qr
 * @date 2022/2/16$
 */

public class SqlExecute {

    static SqlSession session = null;


    public static void execute(String sql) {
        try {
            final Connection connection = initSession(session);
            final int i = connection.prepareStatement(sql).executeUpdate();
            session.commit();
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Long queryVersion(String sql) {
        try {
            final Connection connection = initSession(session);
            final ResultSet resultSet = connection.prepareStatement(sql).executeQuery();
            final Long version = resultSet.getLong("version");
            session.commit();
            session.close();
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void updateSql(String sql) {
        try {
            final Connection connection = initSession(session);
            final int i = connection.prepareStatement(sql).executeUpdate();
            session.commit();
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private static Connection initSession(SqlSession session) {
        try {
            if (null == session) {
                InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
                session = sqlSessionFactory.openSession();
            }
            final Connection connection = session.getConnection();
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;


    }


    public static void main(String[] args) {
        String sql = "insert into  table_name (列1, 列2) VALUES ('1', '2') ";
        String substring = sql.substring(sql.indexOf("into") + 5, sql.indexOf("(") - 1);
        String tableName = substring + "_version";
        final String replace = sql.replace(substring, tableName);

        System.out.println(replace);
    }
}
